# -*- coding: utf-8 -*-
import pymysql
import logging
import pymongo


class Shici300Pipeline(object):
    def process_item(self, item, spider):
        logging.info(spider)
        return item


class SavetoMysql(object):

    def __init__(self):
        self.conn = pymysql.connect(
            host="127.0.0.1",
            user="root", password="root",
            database="blog",
            charset="utf8")
        self.db = self.conn.cursor()

    def process_item(self, item, spider):
        sql = 'insert into article (cid,title,author,content) values (1,%s,%s,%s)'

        title = item['title']
        author = item['author']
        content = item['content']
        try:
            self.db.execute(sql, [title, author, content])
            self.conn.commit()
        except Exception as e:  # 方法一：捕获所有异常
            # 如果发生异常，则回滚
            self.conn.rollback()
        return item


class StorySavetoMysql(object):

    def __init__(self):
        self.conn = pymysql.connect(
            host="127.0.0.1",
            user="root", password="root",
            database="blog",
            charset="utf8")
        self.db = self.conn.cursor()

    def process_item(self, item, spider):
        sql = 'insert into story (title,section_title,content) values ("哥哥，不可以",%s,%s)'

        section_title = item['section_title']
        content = item['content']
        try:
            self.db.execute(sql, [section_title, content])
            self.conn.commit()
        except Exception as e:  # 方法一：捕获所有异常
            # 如果发生异常，则回滚
            self.conn.rollback()
        return item


class SavetoMongo(object):
    def __init__(self):
        client = pymongo.MongoClient("47.92.84.18", 27017)
        self.db = client.test

    def process_item(self, item, spider):

        """
        符合条件的爬虫执行写入
        """
        if spider.name == 'shici':
            self.db.shici300.insert_one({"title": item['title']})

        return item
